<template>
  <div class="love-app">
    <div class="back-button" @click="goBack">
      <svg viewBox="0 0 24 24" fill="currentColor">
        <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
      </svg>
      返回主页
    </div>

    <ChatRoom
      ref="chatRoom"
      title="AI 恋爱大师"
      :chat-id="chatId"
      @send-message="handleSendMessage"
    />
  </div>
</template>

<script>
import ChatRoom from '../components/ChatRoom.vue'
import { createSSEConnection } from '../utils/sse.js'

export default {
  name: 'LoveApp',
  components: {
    ChatRoom
  },
  data() {
    return {
      chatId: '',
      sseClient: null,
      isConnecting: false,
      connectionTimeout: null
    }
  },
  methods: {
    /**
     * 返回主页
     */
    goBack() {
      // 重置连接状态并返回主页
      this.resetConnectionState()
      this.$router.push('/')
    },

    /**
     * 生成聊天室ID
     */
    generateChatId() {
      const timestamp = Date.now()
      const random = Math.random().toString(36).substr(2, 9)
      return `love_${timestamp}_${random}`
    },

    /**
     * 重置连接状态
     */
    resetConnectionState() {
      this.isConnecting = false
      this.$refs.chatRoom.setLoading(false)
      this.$refs.chatRoom.setTyping(false)

      if (this.connectionTimeout) {
        clearTimeout(this.connectionTimeout)
        this.connectionTimeout = null
      }

      if (this.sseClient) {
        this.sseClient.close()
        this.sseClient = null
      }
    },

    /**
     * 处理发送消息
     */
    async handleSendMessage(message) {
      // 防止重复请求 - 检查是否正在连接中
      if (this.isConnecting) {
        console.log('正在处理中，忽略重复请求')
        return
      }

      try {
        this.isConnecting = true
        this.$refs.chatRoom.setLoading(true)
        console.log('开始处理消息:', message)

        // 清除之前的超时定时器
        if (this.connectionTimeout) {
          clearTimeout(this.connectionTimeout)
        }

        // 设置超时定时器，10秒后强制重置状态
        this.connectionTimeout = setTimeout(() => {
          console.warn('连接超时，强制重置状态')
          this.resetConnectionState()
        }, 10000)

        // 关闭之前的连接
        if (this.sseClient) {
          this.sseClient.close()
          this.sseClient = null
        }

        // 构建SSE请求URL
        const url = `http://localhost:8123/api/ai/love_app/chat/sse?message=${encodeURIComponent(message)}&chatId=${this.chatId}`

        console.log('发起SSE连接:', url)

        // 先创建一个空的AI消息气泡
        this.$refs.chatRoom.startNewAIMessage()

        // 创建新的SSE连接
        this.sseClient = createSSEConnection(url, {
          onOpen: (event) => {
            console.log('SSE连接已建立')
            this.$refs.chatRoom.setTyping(true)
            // 连接成功后重置状态
            this.isConnecting = false
            // 清除超时定时器
            if (this.connectionTimeout) {
              clearTimeout(this.connectionTimeout)
              this.connectionTimeout = null
            }
          },

          onMessage: (data) => {
            console.log('收到AI回复:', data)
            this.$refs.chatRoom.setTyping(false)

            try {
              // 处理接收到的数据
              if (data && data.trim()) {
                // 检查是否是结束标志
                if (data.trim() === '[DONE]' || data.trim() === 'data: [DONE]') {
                  this.$refs.chatRoom.completeCurrentAIMessage()
                  this.$refs.chatRoom.setLoading(false)
                  this.sseClient.close()
                  return
                }

                // 处理data:前缀
                let content = data
                if (content.startsWith('data: ')) {
                  content = content.substring(6)
                }

                // 如果是JSON格式，尝试解析
                try {
                  const parsed = JSON.parse(content)
                  content = parsed.content || parsed.message || parsed.data || content
                } catch (e) {
                  // 如果不是JSON，直接使用原始数据
                }

                // 累积更新AI消息
                if (content && content.trim()) {
                  this.$refs.chatRoom.addAIMessage(content, false)
                }
              }
            } catch (error) {
              console.error('处理消息时出错:', error)
            }
          },

          onError: (event) => {
            console.error('SSE连接错误:', event)

            // 只有在没有正常消息的情况下才显示错误
            const lastMessage = this.$refs.chatRoom.messages[this.$refs.chatRoom.messages.length - 1]
            if (!lastMessage || lastMessage.content.trim() === '') {
              this.$refs.chatRoom.addAIMessage('抱歉，连接出现问题，请稍后重试。', true)
            } else {
              this.$refs.chatRoom.completeCurrentAIMessage()
            }

            // 重置连接状态
            this.resetConnectionState()
          },

          onClose: (event) => {
            console.log('SSE连接已关闭')
            this.$refs.chatRoom.completeCurrentAIMessage()

            // 重置连接状态
            this.resetConnectionState()
          }
        })

      } catch (error) {
        console.error('发送消息失败:', error)
        this.$refs.chatRoom.addAIMessage('抱歉，发送消息时出现错误，请稍后重试。', true)

        // 重置连接状态
        this.resetConnectionState()
      }
    }
  },

  created() {
    // 生成聊天室ID
    this.chatId = this.generateChatId()
    console.log('生成聊天室ID:', this.chatId)
  },

  beforeUnmount() {
    // 组件销毁前重置连接状态
    this.resetConnectionState()
  }
}
</script>

<style scoped>
.love-app {
  height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #ff6b6b, #ee5a24);
}

.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  padding: 10px 16px;
  border-radius: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.back-button:hover {
  background: white;
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}

.back-button svg {
  width: 18px;
  height: 18px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .back-button {
    top: 15px;
    left: 15px;
    padding: 8px 12px;
    font-size: 13px;
  }

  .back-button svg {
    width: 16px;
    height: 16px;
  }
}
</style>
